<?php
namespace app\common\model\auth;

use app\common\model\BaseModel;
use org\util\TreeUtil;
use think\Db;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Session;
use think\helper\Str;

class RuleModel extends BaseModel
{
    protected $name = 'auth_rule';
    protected $pk='id';
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    /**
     * 获取缓存数据
     * @return mixed
     * @throws \Exception
     */
    public function getList(){
        if(!Cache::has('auth_rule')){
            $this->updateCache();
        }
        $list = Cache::get('auth_rule');
        return $list;
    }
    /**
     * 获取树型列表
     */
    public function getTreeList(){
        $list = $this->getList();
        $list = array_values($list);
        $treeList = TreeUtil::channelLevel($list,0);
        return $treeList;
    }

    /**
     * 获取部门信息
     * @param $map
     * @return array|\PDOStatement|string|\think\Model|void|null
     */
    public function getInfo($map){
        $info = $this->where($map)->find();
        $list = $this->getList();
        $info = $list[$info['id']];
        return $info;
    }
    /**
     * 缓存数据
     * @return bool
     * @throws \Exception
     */
    public function updateCache(){
        try{
            $list = $this->order('show_order asc')->select();
            $list = $list->isEmpty()?[]:$list->toArray();
            $list = TreeUtil::tree($list,'title'); //转换树型
            $cache=[];
            foreach($list as $k=>$v){
                //取所有下级，包含当前级
                $ids=$v['id']; //当前ID
                $hasChild = 0; //默认无下级
                $v['next_level']=[]; //下级分类
                $child = TreeUtil::channelList($list,$v['id']); //当前ID的所有下级
                $dataView = array_column($child,'id');
                if(!empty($dataView)){
                    $ids.=','.implode(',',$dataView);
                    $hasChild = 1;
                    foreach($child as $kk=>$vv){
                        if($vv['pid']==$v['id']) $v['next_level'][]=$vv;
                    }
                }
                $v['data_view'] = $ids;
                $v['has_child'] = $hasChild;
                //取所有上级
                $parents = array_reverse(TreeUtil::parentChannel($list, $v['id']));
                $path = array_column($parents,'id');
                $fullName = array_column($parents,'title');
                $v['path'] = implode(',',$path);
                $v['full_name'] = implode(',',$fullName);
                $cache[$v['id']] = $v;
            }
            Cache::set('auth_rule',$cache);
        }catch (\Exception $e){
            exception($e->getMessage());
        }
        return true;
    }

    /**
     * 删除部门
     * @param $id
     */
    public function delData($id) {
        $list = $this->getList();
        $deptInfo = $list[$id];
        if($deptInfo['has_child']==1) exception('存在下级规则，不允许删除！');
        $rules = GroupModel::where('','EXP', Db::raw("FIND_IN_SET('{$id}',`rules`)"))->find();
        if($rules) exception('该规则正在使用，不允许删除！');
        $this->where('id',$id)->delete();
    }

    /**
     * 获取子菜单
     */
    public function getSubMenu($id){
        $auth = \org\Auth::instance('admin');
        $sessionKey = Session::get('session_key');
        $loginInfo = $auth->getSessionInfo($sessionKey);
        $rules = $auth->getAuthList($loginInfo['id']);
        $controller = Str::snake(Request::controller());
        $action = Request::action();
        $subMenu = $this->where('pid',$id)->where('is_menu',2)->select()->toArray();
        $i=0; $subMenus = [];
        foreach($subMenu as $k=>$v){
            if(!in_array($v['name'],$rules)) continue;
            $url = array_reverse(explode('/',$v['name']));
            $RuleController = strtolower($url[1]);
            $RuleAction = strtolower(str_replace('.html','',$url[0]));
            $v['active'] = $controller==$RuleController && $action==$RuleAction ? 'active' : '';
            $subMenus[$i] = $v;
            $i++;
        }
        $items=[];
        foreach($subMenus as $v){
            $items[] = '<li class="'.$v['active'].'"><a href="'.$v['name'].'">'.$v['title'].'</a></li>';
        }
        $html = '<ul class="nav nav-tabs">'.implode(PHP_EOL,$items).'</ul>';
        return $html;
    }
}